package com.huaao.micropolice.root.security;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;

import com.huaao.micropolice.core.model.system.User;
import com.huaao.micropolice.core.service.system.UserService;

/**
 * XsAuthenticationFilter
 * 
 * @author liuben
 * 
 */
public class AuthenticationFilter extends FormAuthenticationFilter {
	
    /**
     * 返回URL
     */
    public static final String FALLBACK_URL_PARAM = "fallbackUrl";
    
    @Autowired
    private UserService userService;
	
    @Override
	protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
    	AuthenticationToken token = createToken(request, response);
        if (token == null) {
            throw new IllegalStateException("createToken method implementation returned null. A valid non-null AuthenticationToken must be created in order to execute a login attempt.");
        }
        String username = (String) token.getPrincipal();
        User user = userService.findByUsername(username);
        if (user == null){
        	return onLoginFailure(token, new UnknownAccountException(), request, response);
        }
        try {
        	Subject subject = getSubject(request, response);
            subject.login(token);
            return onLoginSuccess(token, subject, request, response);
        }catch(AuthenticationException e){
        	e.printStackTrace();
            return onLoginFailure(token, e, request, response);
        }
	}
}
